//
//  YKContactsController.m
//  WeChat
//
//  Created by 吴高烽 on 2016/11/7.
//  Copyright © 2016年 吴高烽. All rights reserved.
//

#import "YKContactsController.h"
#import "YKXMPPTool.h"
#import "YKChatViewController.h"
@interface YKContactsController ()<NSFetchedResultsControllerDelegate>{
    NSFetchedResultsController *_resultsContr;
}
/** 好友数组 */
@property (nonatomic ,strong)NSArray *users;

@end
static NSString *reuseIdentifier = @"contactCell";

@implementation YKContactsController

- (void)viewDidLoad {
    [super viewDidLoad];
//    显示好友数据 (XMPPRoster.sqliter)
    [self coreDataUser];
//
    
    
}

-(void)coreDataUser2{
    //    1、上文关联到数据库
    NSManagedObjectContext *context = [YKXMPPTool shareYKXMPPTool].rosterStorage.mainThreadManagedObjectContext ;
    //    2、request对象，请求查询某张表
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"XMPPUserCoreDataStorageObject"];
    //  2.1、 设置排序
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"displayName" ascending:YES];
    request.sortDescriptors= @[sort];
    //    3.执行请求
//    数据库查询，如果内容较多会放在子线程中，而移动端不会很多可以放在主线程中
    _resultsContr = [[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
    _resultsContr.delegate = self ;
    NSError *err = nil ;
   BOOL flag =  [_resultsContr performFetch:&err];
    if (flag) {
        self.users = _resultsContr.fetchedObjects ;
    }
    
}
-(void)coreDataUser{
    //    1、上文关联到数据库
    NSManagedObjectContext *context = [YKXMPPTool shareYKXMPPTool].rosterStorage.mainThreadManagedObjectContext ;
    
    //    2、request对象，请求查询某张表
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"XMPPUserCoreDataStorageObject"];
    //  2.1、 设置排序
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"displayName" ascending:YES];
    request.sortDescriptors= @[sort];
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"subscription!= %@",@"none"];
    request.predicate = pre ;
    //    3、执行请求获取数据
    NSError *error = nil ;
    //    error:(NSError **)error 带有两个** 就需要用到区地址符号了
    NSArray *users = [context executeFetchRequest:request error:&error];
    if (error) {
        YKLog(@"error = %@",error);
    }else{
        self.users = users ;
        YKLog(@"users = %@",users);
    }
//    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:reuseIdentifier];
}
 
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
    YKLog(@"%@--%@",controller,[NSThread currentThread]);
    [self.tableView reloadData];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.users.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
//    if (!cell) {
//        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
//    }
    XMPPUserCoreDataStorageObject *user = self.users [indexPath.row];
    cell.textLabel.text = user.displayName ;
    // 标识用户是否在线 0:在线，1.离开 2：离线
    YKLog(@"%@:在线状态  %@",user.displayName,user.sectionNum);
    NSInteger state = [user.sectionNum integerValue];
    switch (state) {
        case 0:
            cell.detailTextLabel.text = @"在线";
            break;
        case 1:
            cell.detailTextLabel.text = @"离开";
            break;
        case 2:
            cell.detailTextLabel.text = @"离线";
            break ;
        default:
            cell.detailTextLabel.text = @"未知";
            break;
    }
    if (user.photo) {
        cell.imageView.image = user.photo;
    }else{
     NSData *imageData =  [[YKXMPPTool shareYKXMPPTool].avatar photoDataForJID:user.jid];
        cell.imageView.image = [UIImage imageWithData:imageData];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    XMPPUserCoreDataStorageObject *user = self.users [indexPath.row];
    [self performSegueWithIdentifier:@"toChatVcSegue" sender:user.jid];
    //    [self prepareForSegue:@"toChatVcSegue" sender:nil];
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    XMPPUserCoreDataStorageObject *user = self.users [indexPath.row];

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [[YKXMPPTool shareYKXMPPTool].roster removeUser:user.jid];
//        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}



#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    UIViewController *vc = [segue destinationViewController];
    if ([vc isKindOfClass:[YKChatViewController class]]) {
        YKLog(@"%@",sender);
        YKChatViewController *chatvc = (YKChatViewController*)vc ;
        chatvc.friendJid = (XMPPJID*)sender;
    }
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}


@end
